package myschool.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.Reader;

/**
 * @author oldliu
 * @since 1.0
 */
public class MyBatisUtil {
    private static SqlSessionFactory sessionFactory;
    static {
        String resource = "mybatis-config.xml";
        Reader reader = null;
        try {
            reader = Resources.getResourceAsReader(resource);
            sessionFactory = new SqlSessionFactoryBuilder().build(reader);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private MyBatisUtil() {

    }

    public static SqlSession get() {
        return sessionFactory.openSession();
    }

    public static void close(SqlSession se) {
        if (se != null) {
            se.commit();
            se.close();
        }
    }
}
